/*
 * @Copyright (c) 2008 Claudney S. Reis (claudsan@gmail.com)
 * @Page http://cucadigital.com.br/autosave
 * @description JQUERY PLUGIN CUCA AUTOSAVE FORM REQUIRES JQUERY 1.4.1 AND FIREBUG FOR DEBUG INFO.

 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */

/*
 * @Version: 0.7
 * @Release: 2010-10-29
 *
 */

(function($) {

    $.fn.autoSave = function(settings) {

        this.syncAutoSave = null;

        settings = $.extend({
            autoSaveTime: 10000, //TEMPO EM MILISECONDS
            formId: 'autoSaveForm',
            cacheId: 'CUCA_AUTOSAVE',
            cacheExpiresDays: 1,
            debug: false,
            callBack: null
        }, settings);

        settings.cacheId = formId+"_"+settings.cacheId;
        
        function execAutoSave(){

            var dados = $("#"+settings.formId).serializeArray();
            var itens = "";
            if(settings.debug == true)
                console.group("Autosave Form:"+settings.formId);

            for (i = 0; i < dados.length; i++) {
                if(i>0)itens = itens + ",";
                itens = itens + "{";
                itens = itens + "\"name\":\""+dados[i].name+"\"";
                itens = itens + ",\"value\":\""+dados[i].value;
                itens = itens + "\"}";
                
                if(settings.debug == true)
                    console.info("Field:"+dados[i].name+"=>"+dados[i].value);
            }
            if(settings.debug == true)
                console.groupEnd();

            novoCookie(settings.cacheId, "["+itens+"]", settings.cacheExpiresDays);
        }

        function restauraDados(dados){
            var form = jQuery.parseJSON(dados);
            if(settings.debug == true)
                console.group("Autosave Restore Form:"+settings.formId);
            for (i = 0; i < form.length; i++) {
                $("#"+form[i].name).val(form[i].value);
                if(settings.debug == true)
                    console.info("Field:"+form[i].name+"=>"+form[i].value);
            }
            if(settings.debug == true)
                console.groupEnd();
        }
        
        /**
         * CRIA UM NOVO COOKIE
         * @param nome NOME DO COOKIE
         * @param valor VALOR DO COOKIE
         * @param dias DIAS PARA EXPIRACAO
         */
        function novoCookie(nome,valor,dias) {
            var expira = "";
            if (dias) {
                var date = new Date();
                date.setTime(date.getTime()+(dias*24*60*60*1000));
                expira = "; expires="+date.toGMTString();
            }
            document.cookie = nome+"="+valor+expira+"; path=/";
        }

        /**
         * REALIZA LEITURA DO COOKIE
         * @param nome NOME DO COOKIE QUE DESEJA REALIZAR A LEITURA
         */
        function leCookie(nome) {
            var nomePar = nome + "=";
            var parametrosCookie = document.cookie.split(';');
            for(var i=0;i < parametrosCookie.length;i++) {
                var c = parametrosCookie[i];
                while (c.charAt(0)==' ') c = c.substring(1,c.length);
                if (c.indexOf(nomePar) == 0) return c.substring(nomePar.length,c.length);
            }
            return null;
        }


        function stopSave(){
            if(this.syncAutoSave != null){
                clearInterval(this.syncAutoSave);
            }
        }

        var form = $("#"+settings.formId);
        if(form[0].tagName == "FORM"){

            var old = leCookie(settings.cacheId);
            if(old != null){
                restauraDados(old);
            }

            this.syncAutoSave = setInterval(function()
            {
                execAutoSave();
            }, settings.autoSaveTime);
        }else{
            alert("Form inválido/não encontrado("+settings.formId+"-"+$("#"+settings.formId).type+")!");
        }

    };

    $.fn.autoSaveClear = function(settings){
        
        settings = $.extend({
            formId: 'autoSaveForm',
            cacheId: 'CUCA_AUTOSAVE',
            debug: false
        }, settings);
        
        settings.cacheId = formId+"_"+settings.cacheId;

        document.cookie = settings.cacheId+"=; expires=-1; path=/"
        if(settings.debug)console.info("AutoSave Clear:"+settings.cacheId);
    }



})(jQuery);